import { BackendSession, MsgHandler } from "kilom";
import { msgId } from "../../../cfg/msgcfg";
import { getRoom, getRoomIds } from "../../../game/game";

export default class MsgGameMain extends MsgHandler {

    joinRoom(sess: BackendSession, msg: { roomId: number }) {
        let room = getRoom(msg.roomId);
        if (!room) {
            sess.send(msgId.joinRoom, { err: "房间不存在" });
            return;
        }
        room.join(sess.uid);
        sess.syncSetting({ roomId: msg.roomId });
        sess.send(msgId.joinRoom, { roomId: msg.roomId, players: room.players.map(player => ({ uid: player.uid, name: player.name })), chats: room.chats });
    }

    leaveRoom(sess: BackendSession) {
        let room = getRoom(sess.get("roomId"));
        if (!room) {
            sess.send(msgId.leave, { err: "房间不存在" });
            return;
        }
        
        room.exit(sess.uid);
        sess.syncSetting({}, ["roomId"]);
        sess.send(msgId.leave, { roomIds: getRoomIds() });
    }

}